import React, { useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { AuthContainer } from '../../components/AuthContainer';
import { useUserState, useUserActions } from '../../stores';
import styles from './LoginPage.module.css';

const LoginPage: React.FC = () => {
  const navigate = useNavigate();
  const { isLoggedIn, loading, error } = useUserState();
  const { login } = useUserActions();

  useEffect(() => {
    if (isLoggedIn) {
      navigate('/', { replace: true });
    }
  }, [isLoggedIn, navigate]);

  const handleLogin = async (credentials: { username: string; password: string; rememberMe?: boolean }) => {
    const success = await login(credentials);
    if (success) {
      navigate('/', { replace: true });
    }
    // 登录失败时不进行跳转，错误信息会通过error prop传递给Login组件显示
  };

  const handleForgotPassword = () => {
    // TODO: 实现忘记密码功能
    console.log('忘记密码');
  };

  const handleSignIn = async (userData: {
    username: string;
    email: string;
    password: string;
  }) => {
    // TODO: 实现注册功能
    console.log('注册', userData);
  };

  return (
    <div className={styles.loginPage}>
      {/* 左侧装饰区域 */}
      <div className={styles.leftPanel}>
        <div className={styles.brandSection}>
          <div className={styles.logo}>
            <div className={styles.logoIcon}>⚡</div>
            <h1 className={styles.brandTitle}>ESP32 Launchpad</h1>
          </div>
          <p className={styles.brandSubtitle}>
            专业的ESP32固件管理平台
          </p>
          <div className={styles.features}>
            <div className={styles.feature}>
              <div className={styles.featureIcon}>🔧</div>
              <span>固件管理</span>
            </div>
            <div className={styles.feature}>
              <div className={styles.featureIcon}>📱</div>
              <span>设备监控</span>
            </div>
            <div className={styles.feature}>
              <div className={styles.featureIcon}>🚀</div>
              <span>OTA更新</span>
            </div>
            <div className={styles.feature}>
              <div className={styles.featureIcon}>📊</div>
              <span>数据分析</span>
            </div>
          </div>
        </div>
        
      </div>

      {/* 右侧登录区域 */}
      <div className={styles.rightPanel}>
        {/* 装饰性元素 */}
        <div className={styles.decorativeElements}>
          <div className={styles.floatingIcon1}>⚡</div>
          <div className={styles.floatingIcon2}>🔧</div>
          <div className={styles.floatingIcon3}>📱</div>
          <div className={styles.floatingIcon4}>🚀</div>
        </div>
        
        <AuthContainer
          onLogin={handleLogin}
          onSignIn={handleSignIn}
          onForgotPassword={handleForgotPassword}
          loading={loading}
          error={error || undefined}
        />
      </div>
    </div>
  );
};

export default LoginPage;
